<template>
    <div class="default-main">
        <el-card class="!border-none" shadow="never">
            <el-button type="success" @click="handleAdd">新增笔记</el-button>
        </el-card>
        <el-card shadow="never" class="!border-none mt-4">
            <el-table class="mt-4" size="large" v-loading="pager.loading" :data="pager.lists">
                <el-table-column label="标题" prop="title" min-width="200" show-overflow-tooltip />
                <el-table-column label="媒体" prop="image" min-width="120">
                    <template #default="{ row }">
                        <div v-if="row.image && row.image.length > 0" class="flex flex-wrap gap-1">
                            <template v-for="(media, index) in row.image.slice(0, 1)" :key="index">
                                <image-contain
                                    v-if="media.type === 'image'"
                                    :src="media.url"
                                    :width="50"
                                    :height="50"
                                    fit="cover"
                                    :preview-src-list="getImageUrls(row.image)"
                                    :initial-index="getImageIndex(row.image, index)"
                                    preview-teleported
                                    class="cursor-pointer"
                                />
                                <div
                                    v-else-if="media.type === 'video'"
                                    class="relative w-[50px] h-[50px] bg-gray-100 rounded cursor-pointer flex items-center justify-center"
                                    @click="handleVideoPreview(media.url)"
                                >
                                    <el-icon class="text-gray-500"><VideoPlay /></el-icon>
                                </div>
                            </template>
                            <div v-if="row.image.length > 3" class="w-[50px] h-[50px] bg-gray-100 rounded flex items-center justify-center text-xs text-gray-500">
                                +{{ row.image.length - 3 }}
                            </div>
                        </div>
                        <span v-else class="text-tx-secondary">暂无媒体</span>
                    </template>
                </el-table-column>
                <el-table-column label="内容" prop="content" min-width="250" show-overflow-tooltip>
                    <template #default="{ row }">
                        <div class="line-clamp-2">{{ row.content }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="发布时间" prop="publishTime" min-width="180" />
                <el-table-column label="发布人" prop="publisher" min-width="120" />
                <el-table-column label="审核状态" prop="is_checked" min-width="120">
                    <template #default="{ row }">
                        <el-tag
                            :type="getStatusType(row.is_checked)"
                            effect="plain"
                        >
                            {{ getStatusText(row.is_checked) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                        <el-button
                            type="primary"
                            link
                            @click="handleView(row)"
                        >
                            查看详情
                        </el-button>
                        <el-button
                            type="primary"
                            link
                            @click="handleEdit(row)"
                        >
                            编辑
                        </el-button>
                        <el-button
                            type="primary"
                            link
                            @click="handleAudit(row)"
                        >
                            审核
                        </el-button>
                        <el-button
                            type="danger"
                            link
                            @click="handleDelete(row.id)"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>

        <!-- 查看详情弹窗 -->
        <popup
            ref="popupRef"
            title="笔记详情"
            width="800px"
            :footer="false"
        >
            <div v-if="currentStory" class="space-y-4">
                <div>
                    <div class="text-sm text-tx-secondary mb-2">标题</div>
                    <div class="text-base">{{ currentStory.title }}</div>
                </div>
                <div>
                    <div class="text-sm text-tx-secondary mb-2">媒体文件</div>
                    <div v-if="currentStory.image && currentStory.image.length > 0" class="flex flex-wrap gap-2">
                        <template v-for="(media, index) in currentStory.image" :key="index">
                            <image-contain
                                v-if="media.type === 'image'"
                                :src="media.url"
                                :width="120"
                                :height="90"
                                fit="cover"
                                :preview-src-list="getImageUrls(currentStory.image)"
                                :initial-index="getImageIndex(currentStory.image, index)"
                                preview-teleported
                                class="cursor-pointer"
                            />
                            <div
                                v-else-if="media.type === 'video'"
                                class="relative w-[120px] h-[90px] bg-gray-100 rounded cursor-pointer flex items-center justify-center"
                                @click="handleVideoPreview(media.url)"
                            >
                                <el-icon class="text-gray-500 text-2xl"><VideoPlay /></el-icon>
                                <div class="absolute bottom-1 right-1 bg-black bg-opacity-50 text-white text-xs px-1 rounded">视频</div>
                            </div>
                        </template>
                    </div>
                    <span v-else class="text-tx-secondary">暂无媒体文件</span>
                </div>
                <div>
                    <div class="text-sm text-tx-secondary mb-2">内容</div>
                    <div class="text-base whitespace-pre-wrap">{{ currentStory.content }}</div>
                </div>
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <div class="text-sm text-tx-secondary mb-2">发布时间</div>
                        <div class="text-base">{{ currentStory.publishTime || '--' }}</div>
                    </div>
                    <div>
                        <div class="text-sm text-tx-secondary mb-2">发布人</div>
                        <div class="text-base">{{ currentStory.user_id }}</div>
                    </div>
                </div>
                <div>
                    <div class="text-sm text-tx-secondary mb-2">审核状态</div>
                    <el-tag
                        :type="getStatusType(currentStory.is_checked)"
                        effect="plain"
                    >
                        {{ getStatusText(currentStory.is_checked) }}
                    </el-tag>
                </div>
            </div>
        </popup>

        <!-- 审核备注弹窗 -->
        <popup
            ref="auditPopupRef"
            :title="auditTitle"
            width="500px"
            :async="true"
            @confirm="handleAuditSubmit"
        >
            <el-form
                ref="auditFormRef"
                :model="auditForm"
                label-width="80px"
                :rules="auditRules"
            >
                <el-form-item label="审核结果" prop="status">
                    <el-radio-group v-model="auditForm.status">
                        <el-radio :label="1">审核通过</el-radio>
                        <el-radio :label="2">审核拒绝</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- <el-form-item label="审核备注" prop="remark">
                    <el-input
                        v-model="auditForm.remark"
                        type="textarea"
                        :rows="4"
                        placeholder="请输入审核备注"
                        maxlength="200"
                        show-word-limit
                    />
                </el-form-item> -->
            </el-form>
        </popup>

        <!-- 新增/修改笔记弹窗 -->
        <popup
            ref="formPopupRef"
            :title="formTitle"
            width="800px"
            :async="true"
            @confirm="handleFormSubmit"
        >
            <el-form
                ref="formRef"
                :model="formData"
                :rules="formRules"
                label-width="80px"
            >
                <el-form-item label="笔记标题" prop="title">
                    <el-input
                        v-model="formData.title"
                        placeholder="请输入笔记标题（最多20字）"
                        maxlength="20"
                        show-word-limit
                    />
                </el-form-item>
                <el-form-item label="媒体文件" prop="image">
                    <!-- 渲染之前的图片，并加上传新图片功能 -->
                    <div class="space-y-3">
                        <!-- 已上传的媒体文件展示 -->
                        <div v-if="formData.image && formData.image.length > 0" class="flex flex-wrap gap-2">
                            <template v-for="(media, index) in formData.image" :key="index">
                                <div class="relative">
                                    <image-contain
                                        v-if="media.type === 'image'"
                                        :src="media.url"
                                        :width="120"
                                        :height="90"
                                        fit="cover"
                                        :preview-src-list="getImageUrls(formData.image)"
                                        :initial-index="getImageIndex(formData.image, index)"
                                        preview-teleported
                                        class="cursor-pointer"
                                    />
                                    <div
                                        v-else-if="media.type === 'video'"
                                        class="relative w-[120px] h-[90px] bg-gray-100 rounded cursor-pointer flex items-center justify-center"
                                        @click="handleVideoPreview(media.url)"
                                    >
                                        <el-icon class="text-gray-500 text-2xl"><VideoPlay /></el-icon>
                                        <div class="absolute bottom-1 right-1 bg-black bg-opacity-50 text-white text-xs px-1 rounded">视频</div>
                                    </div>
                                    <!-- 删除按钮 -->
                                    <el-button
                                        type="danger"
                                        size="small"
                                        circle
                                        class="absolute -top-2 -right-2"
                                        @click="removeMedia(index)"
                                    >
                                        <el-icon><Close /></el-icon>
                                    </el-button>
                                </div>
                            </template>
                        </div>
                        
                        <!-- 上传组件 -->
                        <el-upload
                            v-if="formData.image.length < 9"
                            class="upload-demo"
                            drag
                            :action="uploadAction"
                            :headers="uploadHeaders"
                            :before-upload="beforeUpload"
                            :on-success="handleUploadSuccess"
                            :on-error="handleUploadError"
                            :show-file-list="false"
                            accept="image/*,video/*"
                        >
                            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                            <div class="el-upload__text">
                                将文件拖到此处，或<em>点击上传</em>
                            </div>
                            <template #tip>
                                <div class="el-upload__tip">
                                    支持图片和视频文件，最多上传9个文件
                                </div>
                            </template>
                        </el-upload>
                    </div>
                </el-form-item>
                <el-form-item label="笔记内容" prop="content">
                    <editor
                        v-model="formData.content"
                        height="300px"
                    />
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>

<script setup lang="ts" name="storyManage">
import { VideoPlay, Close, UploadFilled } from '@element-plus/icons-vue'
import { apiPostLists, apiPostCheck, apiPostAdd, apiPostEdit, apiPostDelete } from '@/api/port'
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'
import { getToken } from '@/utils/auth'
import Editor from '@/components/editor/index.vue'
import Popup from '@/components/popup/index.vue'
import config from '@/config'
// 数组image[{type:'image',url:'/123.jpg'}], 循环遍历把里面的url取出来组成数组 array<string>
const getImageVideoUrls = (image: any[]) => {
    if (!Array.isArray(image)) return []
    return image.map(item => item.url)
}

// 当前查看的笔记
const currentStory = ref<any>(null)

// 审核表单
const auditForm = reactive({
    id: '',
    status: 0,
    remark: ''
})

// 审核表单验证规则
const auditRules = {
    status: [
        { required: true, message: '请选择审核结果', trigger: 'change' }
    ],
    remark: [
        { required: true, message: '请输入审核备注', trigger: 'blur' }
    ]
}

// 弹窗相关
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const auditPopupRef = shallowRef<InstanceType<typeof Popup>>()
const formPopupRef = shallowRef<InstanceType<typeof Popup>>()
const auditFormRef = shallowRef<any>()
const formRef = shallowRef<any>()
const auditTitle = ref('')
const formTitle = ref('')
const formMode = ref('add') // 'add' | 'edit'

// 表单数据
const formData = ref<any>({
    id: '',
    title: '',
    image: [] as any,
    content: ''
})

// 上传相关
const uploadAction = ref(`${config.baseUrl}${config.urlPrefix}/upload/image`)
const uploadHeaders = ref({
    Token: `${getToken()}`
})

// 表单验证规则
const formRules = {
    title: [
        { required: true, message: '请输入笔记标题', trigger: 'blur' },
        // { max: 20, message: '标题不能超过20个字符', trigger: 'blur' }
    ],
    content: [
        { required: true, message: '请输入笔记内容', trigger: 'blur' }
    ]
}

// 新增笔记
const handleAdd = () => {
    formMode.value = 'add'
    formTitle.value = '新增笔记'
    formData.value.id = ''
    formData.value.title = ''
    formData.value.image = []
    formData.value.content = '' 
    formPopupRef.value?.open()
}

// 编辑笔记
const handleEdit = (row: any) => {
    formMode.value = 'edit'
    formTitle.value = '编辑笔记'
    formData.value.id = row.id
    formData.value.title = row.title
    formData.value.image = row.image || []
    formData.value.content = row.content
    formPopupRef.value?.open()
}

// 上传前验证
const beforeUpload = (file: File) => {
    const isImage = file.type.startsWith('image/')
    const isVideo = file.type.startsWith('video/')
    
    if (!isImage && !isVideo) {
        feedback.msgError('只能上传图片或视频文件！')
        return false
    }
    
    const isLt10M = file.size / 1024 / 1024 < 10
    if (!isLt10M) {
        feedback.msgError('文件大小不能超过 10MB！')
        return false
    }
    
    if (formData.value.image.length >= 9) {
        feedback.msgError('最多只能上传9个文件！')
        return false
    }
    
    return true
}

// 上传成功处理
const handleUploadSuccess = (response: any) => {
    console.log(response)
    if (response.code === 1) {
        // const fileType = response.data.type || (response.data.url.includes('.mp4') || response.data.url.includes('.avi') || response.data.url.includes('.mov') ? 'video' : 'image')
        
        const mediaItem = {
            type: 'image',
            url: response.data.uri
        }
        // images.value.push(mediaItem)
        formData.value.image.push(mediaItem)
        feedback.msgSuccess('上传成功')
    } else {
        feedback.msgError(response.msg || '上传失败')
    }
}

// 上传失败处理
const handleUploadError = () => {
    feedback.msgError('上传失败，请重试')
}

// 删除媒体文件
const removeMedia = (index: number) => {
    formData.value.image.splice(index, 1)
}



// 媒体文件排序（视频优先）
const sortMediaFiles = (mediaList: any[]) => {
    if (!Array.isArray(mediaList)) return []
    
    const videos = mediaList.filter(item => {
        if (typeof item === 'string') {
            return item.includes('.mp4') || item.includes('.avi') || item.includes('.mov')
        }
        return item.type === 'video'
    })
    
    const images = mediaList.filter(item => {
        if (typeof item === 'string') {
            return !item.includes('.mp4') && !item.includes('.avi') && !item.includes('.mov')
        }
        return item.type !== 'video'
    })
    
    return [...videos, ...images]
}

// 提交表单
const handleFormSubmit = async () => {
    if (!formRef.value) return
    
    try {
        await formRef.value.validate()
        
        const submitData: any = {
            ...formData.value
        }
        
        if (formMode.value === 'add') {
            // 新增
            delete submitData.id
            await apiPostAdd(submitData)
            feedback.msgSuccess('新增成功')
        } else {
            // 修改
            await apiPostEdit(submitData)
            feedback.msgSuccess('修改成功')
        }
        
        formPopupRef.value?.close()
        getLists()
    } catch (error) {
        if (error !== false) {
            const action = formMode.value === 'add' ? '新增' : '修改'
            feedback.msgError(`${action}失败`)
        }
    }
}



// 分页相关
const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: apiPostLists,
    params: {}
})

// 获取状态类型
const getStatusType = (status: number) => {
    const statusMap = {
        0: 'warning',
        1: 'success',
        2: 'danger'
    }
    return statusMap[status as keyof typeof statusMap] || 'info'
}

// 获取状态文本
const getStatusText = (status: number) => {
    const statusMap = {
        0: '待审核',
        1: '审核通过',
        2: '审核拒绝'
    }
    return statusMap[status as keyof typeof statusMap] || '未知状态'
}

// 查看详情
const handleView = (row: any) => {
    currentStory.value = row
    popupRef.value?.open()
}

// 审核操作
const handleAudit = (row: any) => {
    auditForm.id = row.id
    auditForm.status = 0
    auditForm.remark = ''
    auditTitle.value = '笔记审核'
    auditPopupRef.value?.open()
}

// 提交审核
const handleAuditSubmit = async () => {
    if (!auditFormRef.value) return
    
    try {
        // 表单验证
        await auditFormRef.value.validate()
        
        await apiPostCheck({
            id: auditForm.id,
            is_checked: auditForm.status
        })
        const action = auditForm.status === 1 ? '通过' : '拒绝'
        feedback.msgSuccess(`审核${action}成功`)
        auditPopupRef.value?.close()
        getLists()
    } catch (error) {
        if (error !== false) {
            feedback.msgError('审核失败')
        }
    }
}

// 删除
const handleDelete = async (id: number) => {
    await feedback.confirm('确定要删除这条笔记吗？')
    try {
        // 这里应该调用删除API
        feedback.msgSuccess('删除成功')
        getLists()
    } catch (error) {
        feedback.msgError('删除失败')
    }
}

// 获取图片URL列表（用于预览）
const getImageUrls = (mediaList: any[]) => {
    return mediaList.filter(item => item.type === 'image').map(item => item.url)
}

// 获取图片在预览列表中的索引
const getImageIndex = (mediaList: any[], currentIndex: number) => {
    const imageList = mediaList.filter(item => item.type === 'image')
    const currentMedia = mediaList[currentIndex]
    if (currentMedia.type === 'image') {
        return imageList.findIndex(item => item.url === currentMedia.url)
    }
    return 0
}

// 处理视频预览
const handleVideoPreview = (videoUrl: string) => {
    // 可以在这里实现视频预览功能，比如打开新窗口或使用视频播放器组件
    window.open(videoUrl, '_blank')
}

// 页面激活时获取列表
onActivated(() => {
    getLists()
})
</script>

<style scoped lang="scss">
.line-clamp-2 {
    width: 100%;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
    display: inline-block;
}
</style>